/*
 * $Id: FilePictureModel.java 204 2009-06-18 17:05:54Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.apps.pictureviewer.data;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import deltadesk.apps.pictureviewer.io.PictureFilesFilenameFilter;

/**
 * FilePictureModel
 * 
 * @author Andreas Meyer
 * @version $Revision: 204 $
 */
public class FilePictureModel implements PictureModel {
	
	/** The base folder or file. */
	private File baseFile;
	
	/** The picture array. */
	private Picture[] pictures;


	/**
	 * Construct the model.
	 * 
	 * @param baseFile
	 */
	public FilePictureModel(final File baseFile) {
		
		this.baseFile = baseFile;
	}
	
	/**
	 * @see deltadesk.apps.pictureviewer.data.PictureModel#init()
	 */
	public int init() throws IOException {

		int index = 0;
		File f = null;
		if(baseFile.isFile()) {
			
			f = baseFile;
			baseFile = baseFile.getParentFile();
		}
		final File[] files = baseFile.listFiles(new PictureFilesFilenameFilter());
		
		if(files == null) {
			
			throw new IOException("Specified folder not found.");
		} // end if
		
		if(files.length == 0) {
			
			throw new IOException("No valid picture found in specified folder.");
		} // end if
		
		Arrays.sort(files);

		// resolve index for given file
		if(f != null) {
			
			final int i = Arrays.binarySearch(files, f);
			if(i >= 0) {
				index = i;
			}
		} // end if
		
		// initialize picture array
		pictures = new Picture[files.length];
		for(int i=0; i<files.length; i++) {
			
			final Picture pic = new Picture(); 
			pic.setSource(files[i].toURL());
			pictures[i] = pic;
		} // end for

		return index;
	}
	
	/**
	 * Clear the preloaded images.
	 */
	public void clearImages() {
		
		for(final Picture pic : pictures) {
			pic.setImage(null);
		} // end for
	}
	
	/**
	 * @see deltadesk.apps.pictureviewer.data.PictureModel#getSize()
	 */
	public int getSize() {
		return pictures.length;
	}

	/**
	 * @see deltadesk.apps.pictureviewer.data.PictureModel#getPicture(int)
	 */
	public Picture getPicture(final int index) throws IOException {

		return pictures[index];
	}

}
